package sm.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import sm.codec.api.Codec;
import sm.codec.exception.DecodeException;
import sm.codec.exception.EncodeException;
import sm.codec.type.Logical;
import sm.codec.type.NullValue;

public class LogicalCodec implements Codec {

	@Override
	public Object decode(IoBuffer buffer) throws DecodeException {
		byte logicalByte = buffer.get();
		Object result = null;
		int booleanValue = logicalByte & 0x0F;

		if (booleanValue == 1) {
			result = Logical.TRUE;
		} else if (booleanValue == 0) {
			result = Logical.FALSE;
		} else if (booleanValue == 15) {
			return NullValue.LogicalNull;
		} else {
			result = Logical.UNKNOWN;
		}

		return result;
	}

	@Override
	public void encode(IoBuffer buffer, Object value) throws EncodeException {
		if (value == null || value == NullValue.LogicalNull) {
			buffer.put((byte) 0x4F);
		} else {
			if (value instanceof Logical) {
				Logical logicalValue = (Logical) value;
				if (logicalValue == Logical.TRUE) {
					buffer.put((byte) 0x41);
				} else if (logicalValue == Logical.FALSE) {
					buffer.put((byte) 0x40);
				} else if (logicalValue == Logical.UNKNOWN) {
					buffer.put((byte) 0x42);
				}
			} else if (value instanceof Boolean) {
				boolean booleanValue = (Boolean) value;
				if (booleanValue) {
					buffer.put((byte) 0x41);
				} else {
					buffer.put((byte) 0x40);
				}
			} else {
				throw new EncodeException("The logical type "
						+ value.getClass().getName() + " is not supported.",
						buffer, value);
			}

		}
	}
}
